package liuhao.user.contoller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import liuhao.base.JsonUtil;
import liuhao.base.MD5Util;
import liuhao.base.Ver;
import liuhao.user.entity.UserEntity;
import liuhao.user.service.impl.UserServiceImpl;



public class UserContoller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserServiceImpl service=new UserServiceImpl();
   
	/*http://localhost:8090/liuhao/user.do?method=quitmethod*/	 
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		  
//		  System.out.println("xx");
		  
		  String method=req.getParameter("method");
		  if("regUser".equals(method)){
			  regUser(req,resp);
		  }else if("loginUser".equals(method)){
			  loginUser(req,resp);
		  }else if("upfile".equals(method)){
			  upfile(req,resp);
		  }else if("security".equals(method)){
			  security(req,resp);
		  }else if("quitmethod".equals(method)){
			  try {
				quitmethod(req,resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		  }
		  
		  
	}

	private void quitmethod(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		String a=req.getParameter("username");
		HttpSession session = req.getSession();
		session.invalidate();
		
//		resp.sendRedirect("login/login.jsp");
//		req.getRequestDispatcher("login/login.jsp").forward(req, resp);
		
		service.q(a);
		
		JsonUtil.WriterToJson(a, resp);
		
	}

	private void security(HttpServletRequest req, HttpServletResponse resp) {
		
		Ver v = new Ver();
		BufferedImage bi = v.getImage();
		String a = v.getText();
		
		//v.getText获得具体验证码
		System.out.println(v.getText());
		
		HttpSession session = req.getSession();
		req.setAttribute("pictureSecurity",v.getText());
		session.setAttribute("pictureSecurity",v.getText());
		try {
			v.outPut(bi, resp.getOutputStream());
//			resp.sendRedirect("login.jsp");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}

	
	private void upfile(HttpServletRequest req, HttpServletResponse resp) {
		
		try {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Configure a repository (to ensure a secure temp location is used)
			ServletContext servletContext = this.getServletConfig().getServletContext();
			
			File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
			factory.setRepository(repository);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Parse the request
			List<FileItem> items = upload.parseRequest(req);
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = iter.next();

			    String name = item.getName();
			    String st = item.getString();
			    System.out.println(name);
			    System.out.println(st);
			    System.out.println(item.isFormField());
			    if (item.isFormField()) {
			    	//文件说明
			    	 name = item.getName();
				     st = item.getString();
				    System.out.println(name);
				    System.out.println(st);
			        
			    } else {
			    	
			    	//要上传的文件名
			    	String fileName = item.getName();
			    	
			    	
			    	//服务器路径
			    	String root = req.getSession().getServletContext().getRealPath("/");
			    	
			    	
			    	System.out.println(root);
			    	
			    	File filepath=new File(root+File.separator+fileName);
			    	
			    	
//			    	File filepath=new File(s+"\\main/webapp/liuhaofileupload");
				    try {
				    	
				    	InputStream is = item.getInputStream();
				    	
				    	FileOutputStream fos=new FileOutputStream(filepath);
				    	
				    	byte[] b=new byte[1024];
				    	int len=0;
						while((len =is.read(b))!=-1){
							fos.write(b, 0, len);
							fos.flush();
						}
						//存放在session中
						req.getSession().setAttribute("img",File.separator+fileName);
					
						
						
						
						
						resp.sendRedirect("manage/top.jsp");
						fos.close();
						is.close();
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				    
			    }
			}
		
			
		} catch (FileUploadException e) {
			
			e.printStackTrace();
		}
		
	
		
	}

	private void loginUser(HttpServletRequest req, HttpServletResponse resp) {
		
		String lhName = req.getParameter("lhName");
		String Password = req.getParameter("lhPassword");
		String tps = req.getParameter("tps");
		
		String yzm = (String)req.getSession().getAttribute("pictureSecurity");
		Map<String, Object> map=new HashMap<String, Object>();
		//验证码相同去比较用户名和密码
		if(yzm.equalsIgnoreCase(tps)){
			
			//md5加密
			String lhPassword = MD5Util.md5Encrypt(Password);
			ServletContext session = req.getServletContext();
			
			session.setAttribute("username", lhName);
			
			UserEntity entity=new UserEntity();
			entity.setUsername(lhName);
			entity.setPassword(lhPassword);
			map = service.loginUser(entity);
			
			int rs = (int)map.get("rs");
			session.setAttribute("rs", rs);
			
			JsonUtil.WriterToJson(map, resp);
			
		}else{
			map.put("code","777");
			JsonUtil.WriterToJson(map, resp);
		}
		
		
	}

	private void regUser(HttpServletRequest req, HttpServletResponse resp) {
		
		String lhName = req.getParameter("lhName");
		String Password = req.getParameter("lhPassword");
		//md5加密
		String lhPassword = MD5Util.md5Encrypt(Password);
		
		UserEntity entity=new UserEntity();
		entity.setPassword(lhPassword);
		entity.setUsername(lhName);
		Map<String, Object> map = service.fingUserbyName(entity);
		JsonUtil.WriterToJson(map, resp);
		
	}

}
